package top.withwings.bonus.common.repo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import top.withwings.bonus.common.pojo.IndexedGrantedAuthority;

import java.util.List;

@Repository
public class AuthorityRepo {

    @Autowired
    private NamedParameterJdbcTemplate namedJdbcTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<IndexedGrantedAuthority> findAll() {

        String sql = " select `index` ,authority from authority ";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(IndexedGrantedAuthority.class));

    }

    public IndexedGrantedAuthority findByIndex(int index) {

        String sql = " select `index` ,authority from authority where `index` = ? ";

        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(IndexedGrantedAuthority.class), index);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }


    public List<IndexedGrantedAuthority> findByUserId(int userId) {

        String sql = " select a.`index` ,a.authority from authority a inner join user_authority r on r.authority_index = a.`index` where r.user_id =? ";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(IndexedGrantedAuthority.class), userId);

    }


    public void deleteUserAuthority(int userId) {
        String sql = " delete from user_authority where user_id = ?";

        jdbcTemplate.update(sql, userId);

    }

    public void addUserAuthority(int userId, List<IndexedGrantedAuthority> authorities) {

        String sql = " insert into user_authority (user_id, authority_index) values(?,?)";

        for (IndexedGrantedAuthority authority : authorities) {
            jdbcTemplate.update(sql, userId, authority.getIndex());
        }

    }

}
